"""
扫货时间频率配置对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                            QPushButton, QTableWidget, QTableWidgetItem,
                            QHeaderView, QMessageBox)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QColor

class ScanFrequencyConfigDialog(QDialog):
    """扫货时间频率配置对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("扫货时间频率配置")
        self.resize(500, 400)
        self.setup_ui()
        self.load_configs()
        
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("配置项:")
        title_label.setStyleSheet("font-size: 14px; font-weight: bold;")
        layout.addWidget(title_label)
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(["时间区间", "扫货频率百分比", "操作"])
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
        self.table.horizontalHeader().setDefaultSectionSize(100)
        # 设置表格为不可编辑
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                background-color: white;
                gridline-color: #ebeef5;
            }
            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #ebeef5;
            }
            QTableWidget::item:selected {
                background-color: #ecf5ff;
                color: #409eff;
            }
            QHeaderView::section {
                background-color: #f5f7fa;
                padding: 8px;
                border: none;
                border-bottom: 1px solid #ebeef5;
                border-right: 1px solid #ebeef5;
                font-weight: bold;
                color: #606266;
            }
        """)
        layout.addWidget(self.table)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 新增配置按钮
        self.add_btn = QPushButton("新增配置")
        self.add_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 16px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        self.add_btn.clicked.connect(self.show_add_config_dialog)
        button_layout.addWidget(self.add_btn)
        
        # 更新配置按钮
        update_btn = QPushButton("更新配置")
        update_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 16px;
                background-color: #67c23a;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #85ce61;
            }
        """)
        update_btn.clicked.connect(self.update_configs)
        button_layout.addWidget(update_btn)
        
        layout.addLayout(button_layout)
    
    def load_configs(self):
        """从数据库加载配置数据"""
        try:
            import json
            from com.db.cons_manager import ConsManager
            
            # 从数据库加载配置
            cons_manager = ConsManager()
            config_json = cons_manager.get_value("SCAN_FREQUENCY_CONFIG")
            
            if config_json:
                # 将JSON字符串转换为配置列表
                self.configs = json.loads(config_json)
            else:
                # 如果没有配置，初始化空列表
                self.configs = []
        except Exception as e:
            import logging
            logging.error(f"加载扫货频率配置时出错: {str(e)}")
            self.configs = []
        
        # 更新表格显示
        self.update_table()
    
    def sort_configs(self):
        """按时间顺序对配置进行排序"""
        def get_start_minutes(config):
            time_range = config["time_range"]
            start_time = time_range.split("-")[0]
            start_hour, start_minute = map(int, start_time.split(":"))
            return start_hour * 60 + start_minute
        
        # 按开始时间排序
        self.configs.sort(key=get_start_minutes)
    
    def update_table(self):
        """更新表格显示"""
        # 先排序
        self.sort_configs()
        
        # 清空表格
        self.table.setRowCount(0)
        
        # 重新填充数据
        for row, config in enumerate(self.configs):
            self.table.insertRow(row)
            
            # 时间区间
            time_range_item = QTableWidgetItem(config["time_range"])
            time_range_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 0, time_range_item)
            
            # 扫货频率百分比
            frequency_item = QTableWidgetItem(config["frequency"])
            frequency_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setItem(row, 1, frequency_item)
            
            # 操作按钮
            action_widget = self.create_action_buttons(row)
            self.table.setCellWidget(row, 2, action_widget)
            
            # 设置行高
            self.table.setRowHeight(row, 40)
    
    def create_action_buttons(self, row):
        """创建操作按钮"""
        from PyQt6.QtWidgets import QWidget
        
        action_widget = QWidget()
        action_layout = QHBoxLayout(action_widget)
        action_layout.setContentsMargins(4, 4, 4, 4)
        action_layout.setSpacing(8)
        
        # 编辑按钮
        edit_btn = QPushButton("编辑")
        edit_btn.setFixedSize(45, 25)
        edit_btn.setStyleSheet("""
            QPushButton {
                padding: 0px;
                background-color: #ecf5ff;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                color: #409eff;
            }
            QPushButton:hover {
                background-color: #409eff;
                color: white;
            }
        """)
        # 存储配置数据的索引，而不是表格行索引
        config_index = row
        edit_btn.clicked.connect(lambda checked=False, idx=config_index: self.edit_config(idx))
        action_layout.addWidget(edit_btn)
        
        # 删除按钮
        delete_btn = QPushButton("删除")
        delete_btn.setFixedSize(45, 25)
        delete_btn.setStyleSheet("""
            QPushButton {
                padding: 0px;
                background-color: #fef0f0;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                color: #f56c6c;
            }
            QPushButton:hover {
                background-color: #f56c6c;
                color: white;
            }
        """)
        # 存储配置数据的索引，而不是表格行索引
        config_index = row
        delete_btn.clicked.connect(lambda checked=False, idx=config_index: self.delete_config(idx))
        action_layout.addWidget(delete_btn)
        
        action_layout.addStretch()
        return action_widget
    
    def show_add_config_dialog(self):
        """显示添加配置对话框"""
        from gui.widgets.add_frequency_config_dialog import AddFrequencyConfigDialog
        
        dialog = AddFrequencyConfigDialog(self)
        if dialog.exec():
            # 获取表单数据
            config_data = dialog.get_form_data()
            if config_data:
                # 添加到配置列表
                frequency_str = f"{int(config_data['frequency'] * 100)}%"
                self.configs.append({
                    "time_range": config_data["time_range"],
                    "frequency": frequency_str
                })
                
                # 更新表格显示
                self.update_table()
    
    def edit_config(self, index):
        """编辑配置
        
        Args:
            index: 配置列表中的索引
        """
        from gui.widgets.add_frequency_config_dialog import AddFrequencyConfigDialog
        
        # 检查索引是否有效
        if index < 0 or index >= len(self.configs):
            return
            
        # 直接从配置列表获取数据
        config = self.configs[index]
        time_range = config["time_range"]
        frequency_text = config["frequency"].replace("%", "")
        
        try:
            frequency = float(frequency_text) / 100
        except (ValueError, TypeError):
            frequency = 0.5  # 默认值
        
        # 创建编辑对话框
        dialog = AddFrequencyConfigDialog(self, time_range=time_range, frequency=frequency)
        if dialog.exec():
            # 获取表单数据
            config_data = dialog.get_form_data()
            if config_data:
                # 更新配置列表
                frequency_str = f"{int(config_data['frequency'] * 100)}%"
                self.configs[index] = {
                    "time_range": config_data["time_range"],
                    "frequency": frequency_str
                }
                
                # 更新表格显示
                self.update_table()
    
    def delete_config(self, index):
        """删除配置
        
        Args:
            index: 配置列表中的索引
        """
        # 检查索引是否有效
        if index < 0 or index >= len(self.configs):
            return
            
        reply = QMessageBox.question(
            self,
            "确认删除",
            "确定要删除此配置吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 从配置列表中删除
            del self.configs[index]
            
            # 更新表格显示
            self.update_table()
    
    def check_time_overlap(self):
        """检查时间段是否有交叉
        
        Returns:
            tuple: (是否有交叉, 交叉的时间段列表)
        """
        if len(self.configs) <= 1:
            return False, []
        
        # 将时间范围转换为分钟数进行比较
        time_ranges = []
        for config in self.configs:
            time_range = config["time_range"]
            start_time, end_time = time_range.split("-")
            
            # 转换为分钟数
            start_hour, start_minute = map(int, start_time.split(":"))
            end_hour, end_minute = map(int, end_time.split(":"))
            
            start_minutes = start_hour * 60 + start_minute
            end_minutes = end_hour * 60 + end_minute
            
            # 处理跨午夜的情况（结束时间小于开始时间）
            crosses_midnight = end_minutes < start_minutes
            
            time_ranges.append({
                "original": time_range,
                "start": start_minutes,
                "end": end_minutes,
                "crosses_midnight": crosses_midnight
            })
        
        # 检查是否有交叉
        overlaps = []
        for i in range(len(time_ranges)):
            for j in range(i + 1, len(time_ranges)):
                range1 = time_ranges[i]
                range2 = time_ranges[j]
                
                # 判断是否有交叉
                has_overlap = False
                
                # 检查是否是相同的边界点（一个的结束时间等于另一个的开始时间）
                is_boundary_same = (range1["end"] == range2["start"]) or (range2["end"] == range1["start"])
                
                # 如果是相同的边界点，不算交叉
                if is_boundary_same:
                    has_overlap = False
                # 如果两个时间段都跨午夜，必然有交叉
                elif range1["crosses_midnight"] and range2["crosses_midnight"]:
                    has_overlap = True
                # 如果第一个时间段跨午夜
                elif range1["crosses_midnight"]:
                    # 如果第二个时间段的开始时间在午夜前或结束时间在午夜后，则有交叉
                    if range2["start"] < range1["end"] or range2["end"] > range1["start"]:
                        has_overlap = True
                # 如果第二个时间段跨午夜
                elif range2["crosses_midnight"]:
                    # 如果第一个时间段的开始时间在午夜前或结束时间在午夜后，则有交叉
                    if range1["start"] < range2["end"] or range1["end"] > range2["start"]:
                        has_overlap = True
                # 如果都不跨午夜，使用常规判断
                else:
                    if (range1["start"] < range2["end"] and range1["end"] > range2["start"]):
                        has_overlap = True
                
                if has_overlap:
                    overlaps.append((range1["original"], range2["original"]))
        
        return len(overlaps) > 0, overlaps
    
    def update_configs(self):
        """更新配置到数据库"""
        try:
            # 检查时间段是否有交叉
            has_overlap, overlaps = self.check_time_overlap()
            if has_overlap:
                overlap_text = "\n".join([f"{o[0]} 与 {o[1]}" for o in overlaps])
                reply = QMessageBox.warning(
                    self,
                    "时间段交叉警告",
                    f"发现以下时间段有交叉:\n{overlap_text}\n\n是否仍然继续保存？",
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                    QMessageBox.StandardButton.No
                )
                
                if reply == QMessageBox.StandardButton.No:
                    return
            
            import json
            from com.db.cons_manager import ConsManager
            
            # 先按时间顺序对配置进行排序
            self.sort_configs()
            
            # 将配置数据转换为JSON字符串
            config_json = json.dumps(self.configs, ensure_ascii=False)
            
            # 保存到数据库
            cons_manager = ConsManager()
            cons_manager.set_value("SCAN_FREQUENCY_CONFIG", config_json)
            
            QMessageBox.information(self, "提示", "配置更新成功")
            self.close()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置时出错: {str(e)}")
